﻿using System;
using System.Windows.Forms;
using DevExpress.Utils;
using E4RPDevExpress10;
using E4RPTools;
using RestaurantCommon;

namespace Restaurant.Controls
{
    public partial class RequestUserControl : UserControl
    {
        private Controller _controller;
        private MesaDataSet _tableData;

        #region Properties

        public Controller Controller
        {
            set
            {
                _controller = value;
                productsUserControl.Controller = _controller;
                _controller.RequestShow += delegate { UpdateControl(); };
                _controller.RequestCloseEditors += delegate { CloseEditors(); };
            }
        }

        #endregion

        public RequestUserControl()
        {
            InitializeComponent();
            Load += RequestUserControlLoad;
            FormatGridColumns();
            productsUserControl.ProductSelected += ProductsUserControlProductSelected;
            gridView.CellValueChanging += GridViewCellValueChanging;
            deleteRepositoryItemButtonEdit.ButtonClick += DeleteRepositoryItemButtonEditButtonClick;
            tableLookUpEdit.EditValueChanging += TableLookUpEditEditValueChanging;
        }
        
        #region Private Methods

        private void SetupTableData()
        {
            _tableData = _controller.Tables();
            mesaDataSet.Clear();
            mesaDataSet.Merge(_tableData);
            tableLookUpEdit.Properties.DataSource = mesaDataSet.Mesa;
            tableLookUpEdit.Properties.DisplayMember = mesaDataSet.Mesa.NomeColumn.ToString();
            tableLookUpEdit.Properties.ValueMember = mesaDataSet.Mesa.IdColumn.ToString();
            tableLookUpEdit.Properties.Columns.Clear();
            tableLookUpEdit.Properties.Columns.AddRange(new[] {
                new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Nome", "Nome", 70, FormatType.None, "", true, HorzAlignment.Near)});
        }

        private void SetupGridData()
        {
            gridControl.DataSource = null;
            gridControl.DataMember = "";
            gridControl.DataSource = _controller.Request;
            gridControl.DataMember = _controller.Request.ItemPedido.TableName;
        }

        private void SetDataToControls()
        {
            numberTextEdit.Text = _controller.Request.Pedido[0].Nome;
            if (!_controller.Request.Pedido[0].IsIdMesaNull()) tableLookUpEdit.EditValue = _controller.Request.Pedido[0].IdMesa;
            placesSpinEdit.EditValue = _controller.Request.Pedido[0].NumeroPessoas;
            stateTextEdit.Text = _controller.Request.Pedido[0].Estado;
            startDateEdit.EditValue = _controller.Request.Pedido[0].DataInicio;
            startTimeEdit.EditValue = _controller.Request.Pedido[0].DataInicio;
        }

        private void FormatGridColumns()
        {
            DevExpressHelper.SetColumnAsNumeric(colQuantidade);
            DevExpressHelper.SetColumnAsCurrency(colValorTotal);
            DevExpressHelper.SetColumnAsCurrency(colValorUnitario);
        }

        private void UpdateControl()
        {
            SetupTableData();
            SetDataToControls();
            SetupGridData();
            FormatGridColumns();
            tableLookUpEdit.Enabled = _controller.Request.Pedido[0].Id < 0;
            tableLookUpEdit.ClosePopup();

            productsUserControl.ReadOnly = _controller.Request.Pedido[0].Id > 0 && _controller.Request.Pedido[0].Estado == RequestState.Fechado.ToString();
        }
        
        private Control GetControl(string reference)
        {
            switch (reference)
            {
                case "IdMesa":
                    return tableLookUpEdit;
                default:
                    return null;
            }
        }

        public static bool TryParse(object decimalValue, out decimal convertedValue)
        {
            try
            {
                if (decimalValue == DBNull.Value)
                {
                    convertedValue = 0;
                    return false;
                }
                convertedValue = Convert.ToDecimal(decimalValue);
                return true;
            }
            catch (FormatException)
            {
                convertedValue = 0;
                return false;
            }
        }

      
        #endregion

        public void CloseEditors()
        {
            if (tableLookUpEdit.EditValue != null && (_controller.Request.Pedido[0].IsIdMesaNull() || _controller.Request.Pedido[0].IdMesa != Convert.ToInt64(tableLookUpEdit.EditValue)))
                _controller.Request.Pedido[0].IdMesa = Convert.ToInt64(tableLookUpEdit.EditValue);
            if (_controller.Request.Pedido[0].NumeroPessoas != Convert.ToInt32(placesSpinEdit.EditValue))
                _controller.Request.Pedido[0].NumeroPessoas = Convert.ToInt32(placesSpinEdit.EditValue);
            gridView.CloseEditor();
            gridView.UpdateCurrentRow();
        }

        public void ClearControlErrors()
        {
            dxErrorProvider.SetError(tableLookUpEdit, "");
            dxErrorProvider.SetError(gridControl, "");
        }

        public void SetControlErrors(Result result)
        {
            foreach (Error error in result.Errors)
                dxErrorProvider.SetError(GetControl(error.Reference), error.Message);
        }

        void RequestUserControlLoad(object sender, EventArgs e)
        {
            if (_controller != null)
                productsUserControl.Populate();
        }

        void ProductsUserControlProductSelected(object sender, ProductEventArgs e)
        {
            _controller.AddProduct(e.ProductReference);
        }

        void DeleteRepositoryItemButtonEditButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            _controller.DeleteRequestItem(Convert.ToString(gridView.GetFocusedRowCellValue(colReferencia)));
        }

        void GridViewCellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column == colQuantidade)
            {
                decimal quantity;
                if (!TryParse(e.Value, out quantity))
                    return;
                decimal unitaryValue = Convert.ToDecimal(gridView.GetFocusedRowCellValue(colValorUnitario));
                gridView.SetFocusedRowCellValue(colValorTotal, quantity * unitaryValue);
            }
            if (e.Column == colValorUnitario)
            {
                decimal quantity = Convert.ToDecimal(gridView.GetFocusedRowCellValue(colQuantidade));
                decimal unitaryValue;
                if (!TryParse(e.Value, out unitaryValue))
                    return;
                gridView.SetFocusedRowCellValue(colValorTotal, quantity * unitaryValue);
            }
        }

        void TableLookUpEditEditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            if (e.NewValue != null)
                placesSpinEdit.EditValue = _tableData.Mesa.FindById(Convert.ToInt64(e.NewValue)).NumeroLugares;
        }
    }
}
